<?php

namespace App\Modules\Admin\Services;

use App\Exceptions\ValidationException;
// use App\Jobs\AdminActivityLogQueue;
use App\Modules\Admin\Repositories\Contracts\AdminUserRepository;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Redis;
use Tymon\JWTAuth\Facades\JWTAuth;

class LoginService
{
    private $adminUserRepository;
    private $redis;

    public function __construct(AdminUserRepository $adminUserRepository)
    {
        $this->adminUserRepository = $adminUserRepository;
        $this->redis = Redis::connection('data');

    }

    /**
     * 后台用户登录
     * 密码前端两次MD5, 后台一次MD5后验证
     *
     * @param [type] $param
     * @return array
     */
    public function login($param)
    {
        $search = [
            'account' => $param['username'],
        ];
        $columns = ['admin_uid', 'account', 'password', 'name', 'avatar', 'sex'];

        $adminUser = $this->adminUserRepository->findByFilter($search, $columns);

        if (is_null($adminUser)) {
            throw new ValidationException('数据不存在');
        }

        $booleanValue = Hash::check(md5($param['password']), $adminUser->password);

        if ($booleanValue) {
            // 判断Redis token数据里是否有该用户未过期的token
            $tokenRedis = $this->redis->exists('token:admin:' . $adminUser->admin_uid);
            if (1 == $tokenRedis) {
                $data['token'] = $this->redis->get('token:admin:' . $adminUser->admin_uid);
            } else {
                // 生成token对象
                $tokenObj =  JWTAuth::fromUser($adminUser);
                $data['token'] = $tokenObj;

                // 约定redis缓存过期时间为36000s
                $diffTime = 36000;
                $this->redis->setex('token:admin:' . $adminUser->admin_uid, $diffTime, $tokenObj);
            }

            $adminData = [
                'admin_uid' => (string) $adminUser->admin_uid,
                'account' => $adminUser->account,
                'name' => $adminUser->name,
                'avatar' => $adminUser->avatar,
                'sex' => $adminUser->sex,
            ];
            // 日志记录
            // AdminActivityLogQueue::dispatch('admin_user.login', '后台用户登录', $adminUser);

            $data['admin_user'] = $adminData;
        } else {
            throw new ValidationException('登录错误');
        }

        return $data;
    }

    public function logout($adminUser)
    {
        //删除redis用户信息缓存
        $this->redis->del('token:admin:' . $adminUser->admin_uid);
        //撤销当前token
        $adminUser->currentAccessToken()->delete();

        return 'success';
    }

}
